﻿Imports System.Text
Imports Microsoft.VisualStudio.RegularExpression.Parser
Imports Microsoft.VisualStudio.Text

Namespace Microsoft.VisualStudio.RegularExpression.BraceMatching
	Friend Class RegexBraceMatcher
		Implements IBraceMatcher
		Private snapshot As ITextSnapshot

		Friend Sub New(ByVal snapshot As ITextSnapshot)
			Me.snapshot = snapshot
		End Sub

		Public Function GetBraceMatchingSpans(ByVal caretLocation As Microsoft.VisualStudio.Text.SnapshotPoint) As IList(Of Tuple(Of SnapshotSpan, SnapshotSpan)) Implements IBraceMatcher.GetBraceMatchingSpans
            Dim text = snapshot.GetText()
            Dim braceMatchingSet As New List(Of Tuple(Of SnapshotSpan, SnapshotSpan))

			'Create a parser to parse the regular expression, and return the classification spans defined by it.
			For Each token As Token In snapshot.TextBuffer.Properties.GetProperty(Of ParserRunner)(GetType(ParserRunner)).Parser.Tokens
				If token.MatchBraces AndAlso (token.Start = caretLocation.Position OrElse token.End = caretLocation.Position) Then
					If token.Kind = TokenKind.CaptureName Then
						braceMatchingSet.Add(New Tuple(Of SnapshotSpan, SnapshotSpan)(New SnapshotSpan(snapshot, token.Start + 1, 1), New SnapshotSpan(snapshot, token.End - 1, 1)))
					Else
						braceMatchingSet.Add(New Tuple(Of SnapshotSpan, SnapshotSpan)(New SnapshotSpan(snapshot, token.Start, 1), New SnapshotSpan(snapshot, token.End - 1, 1)))
					End If
				End If
			Next token

			Return braceMatchingSet
		End Function
	End Class
End Namespace